<template>
    <div class="api-detail-container" v-loading="isloading">
        <!-- 接口头部信息 -->
        <div class="api-header">
            <div class="header-left">
                <div class="title-section">
                    <input v-model="editForm.name" class="api-title-input" placeholder="请输入接口名称" />
                    <button class="save-btn" @click="handleSave">
                        <i class="iconfont icon-baocun"></i>
                        <span>{{ props.currentMode === 'edit' ? '保存' : '创建' }}</span>
                    </button>
                    <button class="cancel-btn" @click="handleCancel">
                        <i class="iconfont icon-quxiao"></i>
                        <span>取消</span>
                    </button>
                </div>
                <div class="request-info">
                    <div class="method-path">
                        <select v-model="editForm.method" class="method-select">
                            <option value="GET">GET</option>
                            <option value="POST">POST</option>
                            <option value="PUT">PUT</option>
                            <option value="DELETE">DELETE</option>
                        </select>
                        <input v-model="editForm.path" class="path-input" placeholder="请输入接口路径" />
                    </div>
                    <div class="api-description">
                        <textarea v-model="editForm.description" class="description-textarea"
                            placeholder="请输入接口描述"></textarea>
                    </div>
                </div>
            </div>
            <div class="header-right">
                <div class="api-meta" v-if="props.apiId">
                    <span class="update-time">更新于 {{ formatMinutesTime(api.updated_time) }}</span>
                    <span class="divider">·</span>
                    <span class="modifier">修改者：{{ api.updater_nickname || '-' }}</span>
                </div>
                <button v-if="props.currentMode === 'edit'" v-permission="'project:manage:delete'" class="delete-btn"
                    @click="handleDelete">
                    <IconDelete />
                    <span>删除</span>
                </button>
            </div>
        </div>

        <!-- 请求头 -->
        <div class="section">
            <div class="section-header">
                <h2 class="section-title">请求头</h2>
                <button class="add-btn" @click="addRequestHeader">
                    <IconAdd />
                    添加请求头
                </button>
            </div>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table compact-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>必填</th>
                                <th>说明</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in editForm.request_headers" :key="index">
                                <td>
                                    <input v-model="item.name" class="table-input" placeholder="参数名" />
                                </td>
                                <td>
                                    <select v-model="item.type" class="table-select">
                                        <option value="string">string</option>
                                        <option value="number">number</option>
                                        <option value="boolean">boolean</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="checkbox" v-model="item.required" />
                                </td>
                                <td>
                                    <input v-model="item.description" class="table-input" placeholder="说明" />
                                </td>
                                <td>
                                    <button class="delete-btn" @click="removeRequestHeader(index)">
                                        <IconDelete />
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 请求参数 -->
        <div class="section">
            <div class="section-header">
                <h2 class="section-title">请求参数</h2>
                <button class="add-btn" @click="addRequestParam">
                    <IconAdd />
                    添加请求参数
                </button>
            </div>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table compact-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>必填</th>
                                <th>说明</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template v-for="(item, index) in editForm.request_params" :key="index">
                                <tr>
                                    <td>
                                        <div class="name-input-wrapper">
                                            <input v-model="item.name" class="table-input" placeholder="参数名" />
                                            <IconAdd v-if="item.type === 'object' || item.type === 'array'"
                                                class="expand-icon"
                                                :class="{ 'expanded': expandedItems[`request-${index}`] }"
                                                @click="toggleExpansion(`request-${index}`)" title="展开编辑子属性" />
                                        </div>
                                    </td>
                                    <td>
                                        <select v-model="item.type" class="table-select">
                                            <option value="string">string</option>
                                            <option value="number">number</option>
                                            <option value="boolean">boolean</option>
                                            <option value="object">object</option>
                                            <option value="array">array</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="checkbox" v-model="item.required" />
                                    </td>
                                    <td>
                                        <input v-model="item.description" class="table-input" placeholder="说明" />
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <button v-if="item.type === 'object' || item.type === 'array'"
                                                class="add-nested-btn"
                                                @click="addNestedField(item, 'request', `request-${index}`)"
                                                title="添加子属性">
                                                <IconAdd />
                                            </button>
                                            <button class="delete-btn" @click="removeRequestParam(index)">
                                                <IconDelete />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 递归嵌套对象编辑行 -->
                                <RecursiveEditRow
                                    v-if="(item.type === 'object' || item.type === 'array') && expandedItems[`request-${index}`]"
                                    :item="item" :item-key="`request-${index}`" :expanded-items="expandedItems"
                                    :level="1" @toggle-expansion="toggleExpansion" @add-nested-field="addNestedField"
                                    @remove-nested-field="removeNestedField" />
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 响应参数 -->
        <div class="section">
            <div class="section-header">
                <h2 class="section-title">响应参数</h2>
                <button class="add-btn" @click="addResponseParam">
                    <IconAdd />
                    添加响应参数
                </button>
            </div>
            <div class="section-content">
                <div class="table-container">
                    <table class="api-table compact-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>类型</th>
                                <th>必填</th>
                                <th>说明</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template v-for="(item, index) in editForm.response_params" :key="index">
                                <tr>
                                    <td>
                                        <div class="name-input-wrapper">
                                            <input v-model="item.name" class="table-input" placeholder="参数名" />
                                            <IconAdd v-if="item.type === 'object' || item.type === 'array'"
                                                class="expand-icon"
                                                :class="{ 'expanded': expandedItems[`response-${index}`] }"
                                                @click="toggleExpansion(`response-${index}`)" title="展开编辑子属性" />
                                        </div>
                                    </td>
                                    <td>
                                        <select v-model="item.type" class="table-select">
                                            <option value="string">string</option>
                                            <option value="number">number</option>
                                            <option value="boolean">boolean</option>
                                            <option value="object">object</option>
                                            <option value="array">array</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="checkbox" v-model="item.required" />
                                    </td>
                                    <td>
                                        <input v-model="item.description" class="table-input" placeholder="说明" />
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <button v-if="item.type === 'object' || item.type === 'array'"
                                                class="add-nested-btn"
                                                @click="addNestedField(item, 'response', `response-${index}`)"
                                                title="添加子属性">
                                                <IconAdd />
                                            </button>
                                            <button class="delete-btn" @click="removeResponseParam(index)">
                                                <IconDelete />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 递归嵌套对象编辑行 -->
                                <RecursiveEditRow
                                    v-if="(item.type === 'object' || item.type === 'array') && expandedItems[`response-${index}`]"
                                    :item="item" :item-key="`response-${index}`" :expanded-items="expandedItems"
                                    :level="1" @toggle-expansion="toggleExpansion" @add-nested-field="addNestedField"
                                    @remove-nested-field="removeNestedField" />
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 请求示例和响应示例 -->
        <div class="examples-section">
            <div class="example-column">
                <h2 class="section-title">请求示例</h2>
                <div class="code-block">
                    <div class="code-header">
                        <span>cURL</span>
                        <div class="code-actions" v-loading="loadingRequest">
                            <button class="ai-generate-btn" @click="generateRequestExample" title="AI生成请求示例">
                                <IconAdd />
                                AI生成
                            </button>
                            <button class="insert-example-btn" @click="insertRequestExample" title="插入请求示例模板">
                                <IconAdd />
                                插入示例
                            </button>
                        </div>
                    </div>
                    <textarea v-model="editForm.request_example" class="code-textarea" placeholder="请输入请求示例"
                        :disabled="loadingRequest"></textarea>
                </div>
            </div>

            <div class="example-column">
                <h2 class="section-title">响应示例</h2>
                <div class="code-block">
                    <div class="code-header">
                        <span>JSON</span>
                        <div class="code-actions" v-loading="loadingResponse">
                            <button class="ai-generate-btn" @click="generateResponseExample" title="AI生成响应示例">
                                <IconAdd />
                                AI生成
                            </button>
                            <button class="insert-example-btn" @click="insertResponseExample" title="插入响应示例模板">
                                <IconAdd />
                                插入示例
                            </button>
                        </div>
                    </div>
                    <textarea v-model="editForm.response_example" class="code-textarea" placeholder="请输入响应示例"
                        :disabled="loadingResponse"></textarea>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch, inject } from 'vue';
import { getApiDetail, updateApiDetail, createApiDetail, deleteApi } from '@/common/apis/project/index.ts';
import { formatMinutesTime } from '@/common/utils/datetime.ts';
import RecursiveEditRow from './RecursiveEditRow.vue';
import { ApiDetail } from '@/common/apis/project/type';
import { useEditorStore } from '@/store/modules/editStatus.ts';
import router from '@/router';
import { useRoute } from 'vue-router';
import { isEqual, cloneDeep } from 'lodash';

const props = defineProps({
    apiId: {
        type: Number
    },
    moduleId: {
        type: Number
    },
    currentMode: {
        type: String,
    }
});

const emit = defineEmits<{
    save: [data: any];
    cancel: [];
    hasChanges: [hasChanges: boolean];
    delete: any;
}>();
const editorStore = useEditorStore();
const route = useRoute();
const isloading = ref(false);
const refreshSidebar = inject('refreshSidebar');
const loadingRequest = ref(false);
const loadingResponse = ref(false);

// 原始数据备份
const originalData = ref<ApiDetail>({
    name: '',
    method: '',
    path: '',
    description: '',
    updated_time: '',
    updater_nickname: '',
    request_headers: [],
    request_params: [],
    response_params: [],
    request_example: '',
    response_example: ''
});

const api = ref<ApiDetail>({
    name: '',
    method: '',
    path: '',
    description: '',
    updated_time: '',
    updater_nickname: '',
    request_headers: [],
    request_params: [],
    response_params: [],
    request_example: '',
    response_example: ''
});

// 编辑表单数据
const editForm = reactive<ApiDetail>({
    name: '',
    method: '',
    path: '',
    description: '',
    updated_time: '',
    updater_nickname: '',
    request_headers: [],
    request_params: [],
    response_params: [],
    request_example: '',
    response_example: ''
});

// 展开状态管理
const expandedItems = ref<Record<string, boolean>>({});

// 切换展开状态
const toggleExpansion = (itemKey: string) => {
    expandedItems.value[itemKey] = !expandedItems.value[itemKey];
};

// 检测是否有未保存的更改
const hasUnsavedChanges = () => {
    return !isEqual(originalData.value, editForm);
};

// 监听编辑表单变化，通知父组件
watch(editForm, () => {
    editorStore.setHasUnsavedChanges(hasUnsavedChanges());
}, { deep: true });

// 添加请求头
const addRequestHeader = () => {
    editForm.request_headers.push({
        name: '',
        type: 'string',
        required: false,
        description: ''
    });
};

// 移除请求头
const removeRequestHeader = (index: number) => {
    editForm.request_headers.splice(index, 1);
};

// 添加请求参数
const addRequestParam = () => {
    editForm.request_params.push({
        name: '',
        type: 'string',
        required: false,
        description: ''
    });
};

// 移除请求参数
const removeRequestParam = (index: number) => {
    editForm.request_params.splice(index, 1);
};

// 添加响应参数
const addResponseParam = () => {
    editForm.response_params.push({
        name: '',
        type: 'string',
        required: false,
        description: ''
    });
};

// 移除响应参数
const removeResponseParam = (index: number) => {
    editForm.response_params.splice(index, 1);
};

// 添加嵌套字段
const addNestedField = (item: any, parentKey: string, itemKey: string) => {
    expandedItems.value[itemKey] = true;
    if (!item.fields) {
        item.fields = [];
    }
    item.fields.push({
        name: '',
        type: 'string',
        required: false,
        description: ''
    });

};

// 移除嵌套字段
const removeNestedField = (item: any, fieldIndex: number, parentKey: string) => {
    if (item.fields) {
        item.fields.splice(fieldIndex, 1);
    }
};
// 插入请求示例模板
const insertRequestExample = () => {
    const requestTemplate = `{
     "id": 20
}`;

    editForm.request_example = requestTemplate;
};

// 插入响应示例模板
const insertResponseExample = () => {
    const responseTemplate = `{
  "code": 200,
  "message": "success",
  "data": {
    "id": 123,
    "username": "john_doe",
    "email": "john@example.com",
    "created_at": "2024-01-01T00:00:00Z"
  }
}`;

    editForm.response_example = responseTemplate;
};

// AI生成示例
const generateExample = async (data: any, type: string) => {
    if (type === 'request') {
        loadingRequest.value = true;
        editForm.request_example = '';
    } else {
        loadingResponse.value = true;
        editForm.response_example = '';
    }
    const endpoint = 'https://api.deepseek.com/chat/completions';
    const headers = {
        "Content-Type": "application/json",
        "Authorization": `Bearer sk-78d1c9032fae44cea79142123606d824`
    };
    try {
        const response = await fetch(endpoint, {
            method: "post",
            headers,
            body: JSON.stringify({
                model: 'deepseek-chat',
                messages: [{ role: 'user', content: `${JSON.stringify(data)}这是一个${type === 'request' ? '请求' : '响应'}参数的数据结构我现在需要写他的请求示例，你能根据他的数据结构名称和类型，以及描述来帮我生成一个吗，简短一点，并返回json格式` }],
                stream: true,
            })
        });
        if (response.body) {
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let done = false;
            let buffer = '';

            while (!done) {
                const { value, done: doneReading } = await reader.read();
                done = doneReading;
                const chunkValue = buffer + decoder.decode(value);
                buffer = '';
                const lines = chunkValue.split('\n').filter(line => line.startsWith('data: ') && line !== 'data: [DONE]');

                for (const line of lines) {
                    const incoming = line.slice(6);
                    try {
                        const data = JSON.parse(incoming);
                        const delta = data.choices[0].delta?.content || '';

                        if (delta) {
                            if (type === 'request') {
                                editForm.request_example += delta;
                            } else {
                                editForm.response_example += delta;
                            }
                        }
                    } catch (error) {
                    }
                }
            }
        }
    } catch {

    } finally {
        if (type === 'request') {
            loadingRequest.value = false;
            ElMessage.success('请求示例生成成功');
        } else {
            loadingResponse.value = false;
            ElMessage.success('响应示例生成成功');
        }

    }
};

// 验证参数是否完整
const validateParameters = (params: any[], paramType: string) => {
    for (let i = 0; i < params.length; i++) {
        const param = params[i];
        // 检查参数名是否为空
        if (!param.name || param.name.trim() === '') {
            return true; // 有缺失参数
        }
        // 如果是嵌套参数，递归检查子参数
        if (param.fields && param.fields.length > 0) {
            if (validateNestedParameters(param.fields)) {
                return true; // 有缺失参数
            }
        }
    }
    return false; // 没有缺失参数
};

// 验证嵌套参数
const validateNestedParameters = (fields: any[]) => {
    for (let i = 0; i < fields.length; i++) {
        const field = fields[i];
        if (!field.name || field.name.trim() === '') {
            return true; // 有缺失参数
        }
        // 递归检查更深层的嵌套
        if (field.fields && field.fields.length > 0) {
            if (validateNestedParameters(field.fields)) {
                return true; // 有缺失参数
            }
        }
    }
    return false; // 没有缺失参数
};

// AI生成请求示例
const generateRequestExample = async () => {
    if (editForm.request_params.length === 0) {
        ElMessage.info('请先添加请求参数');
        return;
    }
    if (validateParameters(editForm.request_params, '请求')) {
        ElMessage.warning('请求参数名称不能为空');
        return;
    }
    ElMessage('开始AI生成请求示例...');
    await generateExample(editForm.request_params, 'request');
};

// AI生成响应示例
const generateResponseExample = async () => {
    if (editForm.response_params.length === 0) {
        ElMessage.info('请先添加响应参数');
        return;
    }
    if (validateParameters(editForm.response_params, '响应')) {
        ElMessage.warning('响应参数名称不能为空');
        return;
    }
    ElMessage('开始AI生成响应示例...');
    await generateExample(editForm.response_params, 'response');
};

// 保存或创建
const handleSave = async () => {
    if (!hasUnsavedChanges() && props.currentMode === 'edit') {
        emit('cancel');
        return;
    }
    editorStore.setHasUnsavedChanges(false);
    isloading.value = true;
    try {
        const apiData = {
            id: props.apiId,
            ...editForm,
            module_id: props.currentMode === 'add' ? Number(route.query.moduleId) : null,
        };
        const _method = props.currentMode === 'edit' ? updateApiDetail : createApiDetail;

        const res = await _method(apiData);
        ElMessage.success(`${res.message}`);
        emit('save', res.data);
    } catch (error) {
        ElMessage.error({ message: '保存失败，请重试' });
    } finally {
        isloading.value = false;
    }
};

// 删除
const handleDelete = async () => {
    ElMessageBox.confirm(
        `确认删除 "${editForm.name}" 该接口吗？此操作不可撤销`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await deleteApi({ id: props.apiId });
            ElMessage.success(`${res.message}`);
            await refreshSidebar({ id: res.data.module_id, isReload: true, type: 'module' });
            router.replace({
                path: `/project/${route.params.id}`,
                query: { ...route.query, mode: 'view' }
            });
        })
        .catch(() => {
        });
};

// 取消
const handleCancel = () => {
    emit('cancel');
};

// 加载API详情
onMounted(async () => {
    if (props.apiId && props.currentMode === 'edit') {
        isloading.value = true;
        try {
            const response = await getApiDetail({ id: props.apiId }) as any;
            const apiData = response.data as ApiDetail;
            api.value = apiData;

            // 初始化编辑表单
            const formData = {
                name: apiData.name,
                method: apiData.method,
                path: apiData.path,
                description: apiData.description,
                updated_time: apiData.updated_time,
                updater_nickname: apiData.updater_nickname,
                request_headers: Array.isArray(apiData.request_headers) ? [...apiData.request_headers] : [],
                request_params: Array.isArray(apiData.request_params) ? [...apiData.request_params] : [],
                response_params: Array.isArray(apiData.response_params) ? [...apiData.response_params] : [],
                request_example: apiData.request_example || '',
                response_example: apiData.response_example || ''
            };

            Object.assign(editForm, formData);
            // 深拷贝保存原始数据备份
            originalData.value = cloneDeep(formData);
        } catch (error) {
        } finally {
            isloading.value = false;
        }
    } else {
        // 创建模式，初始化空数据
        const emptyData = {
            name: '',
            method: 'GET',
            path: '',
            description: '',
            updated_time: '',
            updater_nickname: '',
            request_headers: [],
            request_params: [],
            response_params: [],
            request_example: '',
            response_example: ''
        };
        Object.assign(editForm, emptyData);
        // 深拷贝保存原始数据备份
        originalData.value = cloneDeep(emptyData);
    }
});
</script>

<style scoped lang="less">
.api-detail-container {
    width: 100%;
    height: 100vh;
    padding: 24px;
    background: var(--bg-primary);
    overflow-y: auto;
    position: relative;
    box-sizing: border-box;
}

// 确保父容器也有滚动
:deep(body),
:deep(html) {
    height: 100%;
    overflow-y: auto;
    background: var(--bg-tertiary);
}

.api-header {
    position: relative;
    margin-bottom: 20px;
    padding: 20px;
    background: var(--card-bg);
    border-radius: 8px;
    box-shadow: var(--shadow-light);
    border: 1px solid var(--border-light);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;

    .header-left {
        flex: 1;

        .title-section {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 12px;

            .api-title-input {
                font-size: 20px;
                font-weight: 700;
                color: var(--primary-color);
                background: transparent;
                border: none;
                border-bottom: 2px solid var(--border-light);
                padding: 8px 0;
                outline: none;
                transition: border-color 0.3s ease;
                margin: 0;
                letter-spacing: -0.5px;

                &:focus {
                    border-color: var(--primary-color);
                }

                &::placeholder {
                    color: var(--text-secondary);
                }
            }

            .save-btn,
            .cancel-btn {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 4px 8px;
                background: var(--primary-color);
                border: 1px solid var(--border-light);
                border-radius: 6px;
                cursor: pointer;
                font-size: 10px;
                font-weight: 500;
                color: white;
                transition: all 0.3s ease;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);

                &:hover {
                    background: var(--primary-color);
                    color: white;
                    border-color: var(--primary-color);
                    transform: translateY(-1px);
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                }

                &:active {
                    transform: translateY(0);
                }

                i {
                    font-size: 12px;
                }

                span {
                    font-size: 12px;
                }
            }

            .cancel-btn {
                background: var(--bg-tertiary);
                color: var(--text-secondary);

                &:hover {
                    background: var(--border-light);
                    color: var(--text-primary);
                }
            }
        }

        .request-info {
            .method-path {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-bottom: 12px;

                .method-select {
                    padding: 6px 12px;
                    border: 1px solid var(--border-light);
                    border-radius: 6px;
                    background: var(--bg-secondary);
                    color: var(--text-primary);
                    font-size: 14px;
                    font-weight: 600;
                    cursor: pointer;
                    outline: none;

                    &:focus {
                        border-color: var(--primary-color);
                    }
                }

                .path-input {
                    flex: 1;
                    padding: 6px 12px;
                    border: 1px solid var(--border-light);
                    border-radius: 6px;
                    background: var(--bg-secondary);
                    color: var(--text-primary);
                    font-size: 14px;
                    outline: none;

                    &:focus {
                        border-color: var(--primary-color);
                    }

                    &::placeholder {
                        color: var(--text-secondary);
                    }
                }
            }

            .api-description {
                .description-textarea {
                    width: 100%;
                    min-height: 24px;
                    padding: 8px 12px;
                    border: 1px solid var(--border-light);
                    border-radius: 6px;
                    background: var(--bg-secondary);
                    color: var(--text-primary);
                    font-size: 14px;
                    resize: vertical;
                    outline: none;

                    &:focus {
                        border-color: var(--primary-color);
                    }

                    &::placeholder {
                        color: var(--text-secondary);
                    }
                }
            }
        }
    }

    .header-right {
        .api-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            color: var(--text-secondary);

            .divider {
                color: var(--border-light);
            }
        }

        .delete-btn {
            position: absolute;
            right: 20px;
            bottom: 20px;
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 8px;
            background: #ef4444;
            border: 1px solid var(--border-light);
            border-radius: 6px;
            cursor: pointer;
            font-size: 10px;
            font-weight: 500;
            color: white;

            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);

            &:hover {
                background: #ef4444;
                color: white;
                border-color: #ef4444;
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            &:active {
                transform: translateY(0);
            }

            i {
                font-size: 12px;
            }

            span {
                font-size: 12px;
            }
        }
    }
}

.section {
    margin-bottom: 16px;
    padding: 16px;
    background: var(--card-bg);
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--border-light);
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--primary-color);
            margin: 0 0 12px 0;
            padding-bottom: 6px;
            border-bottom: 1px solid var(--border-color);
            position: relative;

            &::after {
                content: '';
                position: absolute;
                bottom: -1px;
                left: 0;
                width: 40px;
                height: 1px;
                background: var(--primary-color);
                border-radius: 1px;
            }
        }

        .add-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
                background: var(--primary-light);
                transform: translateY(-1px);
            }
        }
    }
}

.table-container {
    overflow-x: auto;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    width: 100%;

    .api-table {
        width: 100%;
        border-collapse: collapse;
        border: none;
        border-radius: 6px;
        overflow: hidden;
        background: var(--card-bg);
        table-layout: fixed;

        th,
        td {
            padding: 10px 12px;
            text-align: left;
            border: 1px solid var(--border-light);
            word-wrap: break-word;
            overflow-wrap: break-word;
        }

        th {
            background: var(--table-header-bg);
            font-weight: 600;
            color: var(--text-primary);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        td {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 500;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover {
            background: rgba(107, 114, 128, 0.1) !important;
            transition: background-color 0.2s ease;
        }

        // 三列表格（响应参数）
        th:nth-child(1),
        td:nth-child(1) {
            width: 30%;
        }

        th:nth-child(2),
        td:nth-child(2) {
            width: 15%;
        }

        th:nth-child(3),
        td:nth-child(3) {
            width: 55%;
        }

        // 四列表格（请求头和请求参数）
        &.compact-table {

            th:nth-child(1),
            td:nth-child(1) {
                width: 25%;
            }

            th:nth-child(2),
            td:nth-child(2) {
                width: 15%;
            }

            th:nth-child(3),
            td:nth-child(3) {
                width: 15%;
            }

            th:nth-child(4),
            td:nth-child(4) {
                width: 35%;
            }

            th:nth-child(5),
            td:nth-child(5) {
                width: 10%;
            }
        }

        // 表格输入框样式
        .table-input {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid transparent;
            background: transparent;
            color: var(--text-primary);
            font-size: 12px;
            outline: none;

            &:focus {
                border-color: var(--primary-color);
                background: var(--bg-secondary);
            }

            &::placeholder {
                color: var(--text-secondary);
            }
        }

        .table-select {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid transparent;
            background: transparent;
            color: var(--text-primary);
            font-size: 12px;
            outline: none;
            cursor: pointer;

            &:focus {
                border-color: var(--primary-color);
                background: var(--bg-secondary);
            }
        }

        // 名称输入框包装器
        .name-input-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;

            // 展开图标样式
            .expand-icon {
                cursor: pointer;
                transition: all 0.3s ease;
                margin-left: 8px;
                font-size: 13px;
                fill: var(--text-secondary);

                &:hover {
                    fill: var(--primary-color);
                    transform: scale(1.1);
                }

                &.expanded {
                    transform: rotate(45deg);
                    fill: var(--primary-color);
                }
            }
        }
    }
}

// 操作按钮组
.action-buttons {
    display: flex;
    align-items: center;
    gap: 4px;

    .add-nested-btn {
        padding: 4px 6px;
        background: var(--primary-color);
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 11px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            background: var(--primary-light);
            transform: scale(1.05);
        }
    }
}

.delete-btn {
    padding: 4px 6px;
    background: var(--error-color);
    color: var(--bg-primary);
    border: none;
    border-radius: 4px;
    font-size: 11px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
        background: var(--error-color);
        transform: scale(1.05);
    }
}




// 三列表格（响应参数）
th:nth-child(1),
td:nth-child(1) {
    width: 30%;
}

th:nth-child(2),
td:nth-child(2) {
    width: 15%;
}

th:nth-child(3),
td:nth-child(3) {
    width: 55%;
}

// 四列表格（请求头和请求参数）
&.compact-table {

    th:nth-child(1),
    td:nth-child(1) {
        width: 25%;
    }

    th:nth-child(2),
    td:nth-child(2) {
        width: 15%;
    }

    th:nth-child(3),
    td:nth-child(3) {
        width: 15%;
    }

    th:nth-child(4),
    td:nth-child(4) {
        width: 35%;
    }

    th:nth-child(5),
    td:nth-child(5) {
        width: 10%;
    }
}

.examples-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;

    .example-column {
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--primary-color);
            margin: 0 0 12px 0;
            padding-bottom: 6px;
            border-bottom: 1px solid var(--border-color);
            position: relative;

            &::after {
                content: '';
                position: absolute;
                bottom: -1px;
                left: 0;
                width: 40px;
                height: 1px;
                background: var(--primary-color);
                border-radius: 1px;
            }
        }
    }
}

.code-block {
    border: none;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    background: var(--card-bg);
    transition: all 0.3s ease;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    }

    .code-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: var(--code-header-bg);
        border-bottom: 1px solid var(--border-light);
        font-size: 11px;
        font-weight: 600;
        color: var(--text-primary);
        text-transform: uppercase;
        letter-spacing: 0.5px;

        .code-actions {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .ai-generate-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 5px 10px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
                background: var(--primary-light);
                transform: translateY(-1px);
            }

            :deep(svg) {
                width: 11px;
                height: 11px;
            }
        }

        .insert-example-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 5px 10px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
                background: var(--primary-light);
                transform: translateY(-1px);
            }

            :deep(svg) {
                width: 11px;
                height: 11px;
                fill: currentColor;
            }
        }
    }

    .code-textarea {
        width: 100%;
        min-height: 350px;
        margin: 0;
        padding: 12px;
        border: none;
        background: var(--bg-secondary);
        color: var(--text-primary);
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 12px;
        line-height: 1.5;
        resize: vertical;
        outline: none;

        &::placeholder {
            color: var(--text-secondary);
        }
    }
}
</style>
